import { useState, useEffect, useRef } from 'react';

/**
 * 自适应表格高度 Hook
 * @param extraHeight 额外需要减去的高度（如搜索表单、页头等）
 * @returns 表格容器高度
 */
export function useTableHeight(extraHeight: number = 0) {
  const [height, setHeight] = useState<number>(600);
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const calculateHeight = () => {
      if (containerRef.current) {
        const containerTop = containerRef.current.getBoundingClientRect().top;
        // 计算可用高度：窗口高度 - 容器距顶部距离 - 底部边距 - 额外高度
        const availableHeight = window.innerHeight - containerTop - 24 - extraHeight;
        setHeight(Math.max(400, availableHeight)); // 最小高度 400px
      }
    };

    // 初始计算
    calculateHeight();

    // 监听窗口大小变化
    window.addEventListener('resize', calculateHeight);

    // 延迟再次计算，确保 DOM 渲染完成
    const timer = setTimeout(calculateHeight, 100);

    return () => {
      window.removeEventListener('resize', calculateHeight);
      clearTimeout(timer);
    };
  }, [extraHeight]);

  return { height, containerRef };
}

/**
 * 简化版：直接计算滚动区域高度
 * @param offset 偏移量
 */
export function useScrollHeight(offset: number = 300) {
  const [scrollY, setScrollY] = useState<number>(600);

  useEffect(() => {
    const calculateHeight = () => {
      const height = window.innerHeight - offset;
      setScrollY(Math.max(400, height));
    };

    calculateHeight();
    window.addEventListener('resize', calculateHeight);

    return () => {
      window.removeEventListener('resize', calculateHeight);
    };
  }, [offset]);

  return scrollY;
}

